<!-- 工艺明细 -->
<template>
  <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
    <el-form-item>
      <el-text>正在编辑: {{ tech.name }} </el-text>
    </el-form-item>
    <el-form-item>

    </el-form-item>
  </el-form>

  <!-- <el-radio-group v-model="viewType" style="margin-bottom: 10px;">
    <el-radio-button label="编辑下发参数" value="edit" />
    <el-radio-button label="查看运行参数" value="query" />

  </el-radio-group> -->

  <div v-show="viewType == 'edit'">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="search" @click="handleQuery">刷新</el-button>
        <el-button type="primary" plain icon="refresh" @click="handleSync">同步结构</el-button>
        <el-button type="primary" plain icon="download" @click="handleSend">下发工参</el-button>
        <el-button type="primary" plain icon="coffee" @click="handleSyncValues">将运行参数存为设定参数</el-button>
      </el-col>
    </el-row>
    <el-table :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="信号名称" align="center" prop="name" />
      <!-- <el-table-column label="信号类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="listTypeOptions" :config="{label: 'label', value: 'value'}"  :value="[scope.row.type]" />
        </template>
</el-table-column> -->

      <el-table-column label="设定值" align="center" prop="configValue" />
      <el-table-column label="运行值" align="center" prop="runValue" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template #default="scope">
          <div v-if="scope.row.id > 0">
            <el-button text size="small" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <!-- <el-button text size="small" icon="delete" @click="handleDelete(scope.row)" >删除 </el-button> -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" v-show="total > 0" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

  </div>

  <!-- 添加或修改参数配置对话框 -->
  <el-dialog :title="title" v-model="open" draggable width="500px" append-to-body>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-row :gutter="20">


        <el-col :lg="12">
          <el-form-item label="参数名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入参数名称" :disabled="true" />
          </el-form-item>
        </el-col>



        <el-col :lg="12">
          <el-form-item label="设定值" prop="configValue">
            <el-input v-model="form.configValue" placeholder="设定值" />
          </el-form-item>
        </el-col>


      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button text @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="dictData">
import { listCksTechniqueDetails, getCksTechniqueDetails, delCksTechniqueDetails, addCksTechniqueDetails, updateCksTechniqueDetails, addCksTechniqueLog, syncCksTechnique,updateConfigValues } from '@/api/business/ckstechniquedetails'
import { listData, getData, delData, addData, updateData } from '@/api/system/dict/data'
import { listType, getType } from '@/api/system/dict/type'
const { proxy } = getCurrentInstance()
const props = defineProps({
  tech: {
    type: Object,
    default: { id: 0 }
  }
})

const ids = ref([])
const selectItems = ref([])
const loading = ref(false)


const viewType = ref('edit')
// 总条数
const total = ref(0)
// 字典表格数据
const dataList = ref([])
// 默认字典类型
const defaultDictType = ref('')
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 数据标签回显样式
const listTypeOptions = ref([
  {
    value: 1,
    label: 'Upper-Send',
    listClass: 'info'
  },
  {
    value: 2,
    label: 'Plc-Confirm',
    listClass: 'success'
  },
  {
    value: 3,
    label: '工艺参数',
    listClass: 'primary'
  }
])


// 状态数据字典
const statusOptions = ref([])
// 类型数据字典
const typeOptions = ref([])
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  dictName: undefined,
  dictType: undefined,
  status: undefined
})
// 表单参数

const formRef = ref()
const state = reactive({
  form: {
    techniqueId: props.tech.id
  },
  rules: {
    blockDb: [{ required: true, message: '不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '不能为空', trigger: 'blur' }],
    dataId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    configValue: [{ required: true, message: '不能为空', trigger: 'blur' }],
    langKey: [{ pattern: /^[A-Za-z].+$/, message: '输入格式不正确,格式：login.ok', trigger: 'blur' }]
  }
})

const { form, rules } = toRefs(state)
/** 查询字典类型详细 */
function getTypeInfo(techId) {
  getType(techId).then((response) => {
    queryParams.dictType = response.data.dictType
    defaultDictType.value = response.data.dictType
    getList()
  })
}
/** 查询字典类型列表 */
function getTypeList() {
  listType().then((response) => {
    typeOptions.value = response.data.result
  })
}

/** 查询字典数据列表 */
function getList() {
  loading.value = true
  queryParams.techniqueId = props.tech.id
  listCksTechniqueDetails(queryParams).then((response) => {
    dataList.value = response.data.result
    total.value = response.data.totalNum
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}
// 表单重置
function reset() {
  form.value = {
    blockDb: form.value?.blockDb,
    name: undefined,
    type: 3,
    dataId: 0,
    configValue: 0,
    techniqueId: props.tech.id,
    id: 0
  }
  proxy.resetForm('formRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryForm')
  queryParams.dictType = defaultDictType.value
  handleQuery()
}
/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加数据'
  form.value.dictType = queryParams.dictType
}
// 多选框选中数据
// function handleSelectionChange(selection) {
//   this.ids = selection.map((item) => item.dictCode)
//   this.single = selection.length != 1
//   this.multiple = !selection.length
// }
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()

  getCksTechniqueDetails(row.id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改数据'
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['formRef'].validate((valid) => {
    if (valid) {
      if (form.value.id > 0) {
        updateCksTechniqueDetails(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addCksTechniqueDetails(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const dictCodes = row.id || ids.value
  proxy
    .$confirm('是否确认删除当前数据项?', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(function () {
      return delCksTechniqueDetails(dictCodes)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
}

watch(
  () => props.tech.id,
  (newVal, oldValue) => {
    if (newVal) {

      //查询工艺明细 
      getList()
    }
  },
  {
    immediate: true,
    deep: true
  }
)

//handleSend
function handleSend() {
  proxy.$modal.loading('正在发送请稍候...')
  const body = { techId: props.tech.id }
  setTimeout(() => {
    //调用后端接口下发配方给PLC
    addCksTechniqueLog(body).then((response) => {
      proxy.$modal.msgSuccess('下发成功')

    }).finally(() => {
      proxy.$modal.closeLoading()
    })

  }, 300);

}
//从模板更新参数结构
function handleSync() {
  //调用后端接口下发配方给PLC
  const body = props.tech
  syncCksTechnique(body).then((response) => {
    proxy.$modal.msgSuccess('同步完成')
    getList()
  })
}

function handleSyncValues(){
  if (ids.value.length === 0) {
    proxy.$modal.msgError('请选择要操作的数据行')
    return
  }
  const body =  { items: selectItems.value }
  updateConfigValues(body).then((response) => {
    proxy.$modal.msgSuccess('操作完成')
    getList()
  })


}

/** 选择条数  */
function handleSelectionChange(selection) {
  
  ids.value = selection.map((item) => item.id)
  selectItems.value = selection.map((item) => { 
    const data = { id:item.id ,runValue:item.runValue,configValue:item.configValue }
    return data
  })

}
</script>